﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using PlayerIO.GameLibrary;
using System.Drawing;


namespace MyGame {
	public class Player : BasePlayer {
		public string Name;
        
        
	}

    [RoomType("Triviador")]
	public class GameCode : Game<Player> {
        private int contador = 0;
        private int respuestasDadas = 0;
        private int respuestasCorrectas = 0;
        Player p1 = new Player();
        Player p2 = new Player();
        Player p3 = new Player();
        long tiempo1;
        long tiempo2;
        long tiempo3;
        private int room = 0;
        // This method is called when an instance of your the game is created
		public override void GameStarted() {
			// anything you write to the Console will show up in the 
			// output window of the development server
			Console.WriteLine("Game is started: " + RoomId);

			// This is how you setup a timer
			AddTimer(delegate {
				// code here will code every 100th millisecond (ten times a second)
			}, 10000);
			
			// Debug Example:
			// Sometimes, it can be very usefull to have a graphical representation
			// of the state of your game.
			// An easy way to accomplish this is to setup a timer to update the
			// debug view every 250th second (4 times a second).
			AddTimer(delegate {
				// This will cause the GenerateDebugImage() method to be called
				// so you can draw a grapical version of the game state.
				RefreshDebugView(); 
			}, 250);
		}

		// This method is called when the last player leaves the room, and it's closed down.
		public override void GameClosed() {
			Console.WriteLine("RoomId: " + RoomId);
		}

		// This method is called whenever a player joins the game
		public override void UserJoined(Player player) {
			// this is how you send a player a message
            if (player.Id >= 4)
            {
                player.Disconnect();
                
            }
			// this is how you broadcast a message to all players connected to the game
			Broadcast("UserJoined", player.Id);
            if (player.Id == 3)
            {
                Broadcast("jugadoresCompletos");
            }
		}


        // This method is called when a player leaves the game
		public override void UserLeft(Player player) {
			Broadcast("UserLeft", player.Id);
            contador--;
		}

		// This method is called when a player sends a message into the server code
        public override void GotMessage(Player player, Message message)
        {
            switch (message.Type)
            {
                // This is how you would set a players name when they send in their name in a 
                // "MyNameIs" message
                case "MyNameIs":
                    player.Name = message.GetString(0);
                    break;
                // En este método se envia un mensaje a los demás usuarios cuando uno de estos elige las preguntas abiertas o cerradas
                case "preguntaAbierta":
                    {
                        int numero = numeroAleatoreo();
                        Broadcast("preguntaAbierta",numero);
                        //Broadcast("Pausado");
                        //WaitSeconds(15);
                        //Broadcast("Continuar");
                    }
                    break;
                case "preguntaCerrada":
                    {
                        int numero = numeroAleatoreo();
                        Broadcast("preguntaCerrada", numero);
                        //Broadcast("Pausado");
                        //WaitSeconds(15);
                        //Broadcast("Continuar");
                    }
                    break;
                case "Win":
                    {
                        respuestasCorrectas++;
                        respuestasDadas++;
                            if (respuestasCorrectas == 1)
                            {
                                p1 = player;
                            }
                            if (respuestasCorrectas == 2)
                            {
                                p2 = player;
                            }
                            if (respuestasCorrectas == 3)
                            {
                                p3 = player;
                            }
                            if (respuestasDadas == 3)
                            {
                                if (respuestasCorrectas == 1)
                                {
                                       p1.Send("Win");
                                }
                                if (respuestasCorrectas == 2)
                                {
                                        p1.Send("Win");
                                        p2.Send("Lose");
                                }
                                if (respuestasCorrectas == 3)
                                {
                                        p1.Send("Win");
                                        p2.Send("Lose");
                                        p3.Send("Lose");
                                }
                              //  WaitSeconds(5);
                                Console.WriteLine("Restarting game");
                                Broadcast("Restart");
                                Console.WriteLine("Broadcast Restart finished");
                                respuestasCorrectas = 0;
                                respuestasDadas = 0;
                             }
      
                            
                    }
                    break;
                case "WinPregCerradas":
                    {
                        respuestasDadas++;
                        respuestasCorrectas++;
                        if (respuestasCorrectas == 1)
                        {
                            p1 = player;
                        }
                        if (respuestasCorrectas == 2)
                        {
                            p2 = player;
                        }
                        if (respuestasCorrectas == 3)
                        {
                            p3 = player;
                        }
                        if (respuestasDadas == 3)
                        {
                            if (respuestasCorrectas == 1)
                            {
                                p1.Send("Win");
                            }
                            if (respuestasCorrectas == 2)
                            {
                                p1.Send("Win");
                                p2.Send("Win");
                            }
                            if (respuestasCorrectas == 3)
                            {
                                p1.Send("Win");
                                p2.Send("Win");
                                p3.Send("Win");
                            }
                            WaitSeconds(5);
                            Console.WriteLine("Restarting game");
                            Broadcast("Restart");
                            Console.WriteLine("Broadcast Restart finished");
                            respuestasCorrectas = 0;
                            respuestasDadas = 0;
                        }
                    }
                    break;
                case "LosePregCerradas":
                    {
                        respuestasDadas++;
                        if (respuestasDadas == 3)
                        {
                            if (respuestasCorrectas == 1)
                            {
                                p1.Send("Win");
                            }
                            if (respuestasCorrectas == 2)
                            {
                                p1.Send("Win");
                                p2.Send("Win");
                            }
                            if (respuestasCorrectas == 3)
                            {
                                p1.Send("Win");
                                p2.Send("Win");
                                p3.Send("Win");
                            }
                            WaitSeconds(5);
                            Console.WriteLine("Restarting game");
                            Broadcast("Restart");
                            Console.WriteLine("Broadcast Restart finished");
                            respuestasCorrectas = 0;
                            respuestasDadas = 0;
                        }
                        
                    }
                    break;
                case "Lose":
                    {
                        respuestasDadas++;
                        if (respuestasDadas == 3)
                        {
                                if (respuestasCorrectas == 1)
                                {
                                        p1.Send("Win");
                                }
                                if (respuestasCorrectas == 2)
                                {
                                        p1.Send("Win");
                                        p2.Send("Lose");
                                }
                                if (respuestasCorrectas == 3)
                                {
                                        p1.Send("Win");
                                        p2.Send("Lose");
                                        p3.Send("Lose");
                                }
                                respuestasCorrectas = 0;
                                respuestasDadas = 0;
                                WaitSeconds(5);
                                Console.WriteLine("Restarting game");
                                Broadcast("Restart");
                                Console.WriteLine("Broadcast Restart finished");
                         }
                    }
                    break;
            }
        }

        private static int numeroAleatoreo()
        {
            Random numero = new Random();
            return numero.Next(0, 14);
        }

        private static void WaitSeconds(double nSecs)
        {
            // Esperar los segundos indicados

            // Crear la cadena para convertir en TimeSpan
            string s = "0.00:00:" + nSecs.ToString().Replace(",", ".");
            TimeSpan ts = TimeSpan.Parse(s);

            // Añadirle la diferencia a la hora actual
            DateTime t1 = DateTime.Now.Add(ts);

            // Esta asignación solo es necesaria
            // si la comprobación se hace al principio del bucle
            DateTime t2 = DateTime.Now;

            // Mientras no haya pasado el tiempo indicado
            while (t2 < t1)
            {
                // Un respiro para el sitema
                // Asignar la hora actual
                t2 = DateTime.Now;
            }
        }

		Point debugPoint;

		// This method get's called whenever you trigger it by calling the RefreshDebugView() method.
		public override System.Drawing.Image GenerateDebugImage() {
			// we'll just draw 400 by 400 pixels image with the current time, but you can
			// use this to visualize just about anything.
			var image = new Bitmap(400,400);
			using(var g = Graphics.FromImage(image)) {
				// fill the background
				g.FillRectangle(Brushes.Blue, 0, 0, image.Width, image.Height);

				// draw the current time
				g.DrawString(DateTime.Now.ToString(), new Font("Verdana",20F),Brushes.Orange, 10,10);

				// draw a dot based on the DebugPoint variable
				g.FillRectangle(Brushes.Red, debugPoint.X,debugPoint.Y,5,5);
			}
			return image;
		}

		// During development, it's very usefull to be able to cause certain events
		// to occur in your serverside code. If you create a public method with no
		// arguments and add a [DebugAction] attribute like we've down below, a button
		// will be added to the development server. 
		// Whenever you click the button, your code will run.
		[DebugAction("Play", DebugAction.Icon.Play)]
		public void PlayNow() {
			Console.WriteLine("The play button was clicked!");
		}

		// If you use the [DebugAction] attribute on a method with
		// two int arguments, the action will be triggered via the
		// debug view when you click the debug view on a running game.
		[DebugAction("Set Debug Point", DebugAction.Icon.Green)]
		public void SetDebugPoint(int x, int y) {
			debugPoint = new Point(x,y);
		}
	}
}
